package com.notetool.util;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringHelper
{

    ////////////////////
    // public static methods
    public static String emptyIfNull (String value)
    {
        if (value == null)
            return "";
        
        return value;
    }
    
    public static String[] split (String value)
    {
        // If value is null, no processing to do
        if (value == null)
            return null;
        
        ArrayList<String> validTokens = new ArrayList<String> ();
        
        // Split String
        String[] tokens = value.trim ().split ("\\s");
        
        // Loop and only take non empty non null tokens
        for (String token : tokens)
            if (!StringHelper.emptyIfNull (token).isEmpty ())
                validTokens.add (token.trim ());
        
        // Return tokens
        return validTokens.toArray (new String[0]);
    }
    
    public static boolean matchesRegEx (String string, String pattern)
    {
        Pattern expPattern = Pattern.compile (pattern);
        Matcher matcher = expPattern.matcher (string);
        
        return matcher.matches ();
    }
    
    public static boolean matchesRegEx (char character, String pattern)
    {
        String charString = String.valueOf (character);
        
        return matchesRegEx (charString, pattern);
    }
    
    public static Pattern makeRegExWildCard (String str, String wildcard)
    {
        if (str == null || str.isEmpty ())
            return Pattern.compile ("[.]*");
        
        if (wildcard == null || wildcard.isEmpty ())
            return Pattern.compile (Pattern.quote (str));
        
        int wildcardLen = wildcard.length ();
        StringBuilder finalEx = new StringBuilder ();
        
        while (true)
        {
            int pos = str.indexOf (wildcard);
            if (pos >= 0)
            {
                finalEx.append (Pattern.quote (str.substring (0, pos)));
                finalEx.append ("[.]*");
                
                int remainderStart = pos + wildcardLen;
                if (remainderStart < str.length ())
                    str = str.substring (remainderStart);
                else
                    break;
            }
            else
            {
                finalEx.append (Pattern.quote (str));
                break;
            }
        }
        
        return Pattern.compile (finalEx.toString ());
    }
    
}
